<template>
	<div class="point-detail-section">
		<!-- 用户基本信息卡片 -->
		<el-card class="user-info-card" v-if="userInfo">
			<div class="user-info">
				<div class="avatar-container">
					<img :src="getAvatarUrl(userInfo.avatar)" alt="用户头像" class="user-avatar"
						@error="handleImageError" />
				</div>
				<div class="user-details">
					<h3 class="user-nickname">{{ userInfo.nickname }}</h3>
					<p class="user-id">用户ID: {{ userInfo.userId }}</p>
					<p class="user-openid">OpenID: {{ userInfo.openid }}</p>
				</div>
				<div class="balance-info">
					<div class="current-balance">
						<span class="balance-label">当前积分</span>
						<span class="balance-value">{{ calculatedCurrentBalance }}</span>
					</div>
				</div>
			</div>
		</el-card>

		<!-- 积分统计卡片 -->
		<el-card class="stats-card" v-if="userInfo">
			<div class="stats-grid">
				<div class="stat-item">
					<div class="stat-value">{{ calculatedTotalEarned }}</div>
					<div class="stat-label">总获得积分</div>
				</div>
				<div class="stat-item">
					<div class="stat-value">{{ calculatedTotalSpent }}</div>
					<div class="stat-label">总消费积分</div>
				</div>
				<div class="stat-item">
					<div class="stat-value">{{ calculatedTotalBonus }}</div>
					<div class="stat-label">总奖励积分</div>
				</div>
				<div class="stat-item">
					<div class="stat-value">{{ calculatedTotalGenerated }}</div>
					<div class="stat-label">总生成次数</div>
				</div>
			</div>
		</el-card>

		<!-- 积分记录表格 -->
		<el-card class="records-card">
			<template #header>
				<div class="card-header">
					<span>积分明细记录</span>
					<el-button type="primary" size="small" @click="refreshData" :loading="loading">
						刷新数据
					</el-button>
				</div>
			</template>

			<div class="table-container">
				<el-table :data="paginatedRecords" style="width: 100%" :max-height="400" v-loading="loading">
					<template #empty>
						<div class="empty-state">
							<el-icon size="48" color="#909399">
								<Document />
							</el-icon>
							<p>暂无积分记录</p>
						</div>
					</template>
					<el-table-column prop="id" label="记录ID" width="80" align="center" />
					<el-table-column prop="type" label="类型" width="120" align="center">
						<template #default="{ row }">
							<el-tag :type="getTypeTag(row.type)" size="small">
								{{ getTypeText(row.type) }}
							</el-tag>
						</template>
					</el-table-column>
					<el-table-column prop="amount" label="积分变动" width="120" align="center">
						<template #default="{ row }">
							<span :class="getAmountClass(row)">
								{{ getAmountDisplay(row) }}
							</span>
						</template>
					</el-table-column>
					<el-table-column prop="balance" label="变动后余额" width="120" align="center" />
					<el-table-column prop="description" label="描述" min-width="200" show-overflow-tooltip />
					<el-table-column prop="createdTime" label="创建时间" width="180" align="center">
						<template #default="{ row }">
							{{ formatDateTime(row.createdTime) }}
						</template>
					</el-table-column>
				</el-table>
			</div>

			<!-- 分页组件 -->
			<div class="pagination-container" v-if="pointRecords.length > 0">
				<el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
					:page-sizes="[10, 20, 50, 100]" :total="pointRecords.length"
					layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange"
					@current-change="handleCurrentChange" />
			</div>
		</el-card>
	</div>
</template>

<script setup>
	import {
		ref,
		computed,
		onMounted
	} from "vue";
	import {
		ElMessage
	} from "element-plus";
	import {
		Document
	} from "@element-plus/icons-vue";
	import usersapi from "../api/usersapi";

	const props = defineProps({
		openid: {
			type: String,
			required: true
		}
	});

	// 响应式数据
	const loading = ref(false);
	const userInfo = ref(null);
	const pointRecords = ref([]);
	const currentPage = ref(1);
	const pageSize = ref(20);

	// 计算分页后的数据
	const paginatedRecords = computed(() => {
		const start = (currentPage.value - 1) * pageSize.value;
		const end = start + pageSize.value;
		return pointRecords.value.slice(start, end);
	});

	// 计算总获得积分（所有 points > 0 的记录）
	const calculatedTotalEarned = computed(() => {
	  return pointRecords.value
	    .filter(record => (record.points || 0) > 0)
	    .reduce((total, record) => total + (record.points || 0), 0);
	});
	
	// 计算总消费积分（所有 points < 0 的记录，取绝对值）
	const calculatedTotalSpent = computed(() => {
	  return Math.abs(
	    pointRecords.value
	      .filter(record => (record.points || 0) < 0)
	      .reduce((total, record) => total + (record.points || 0), 0)
	  );
	});
	
	// 计算当前积分（总获得积分 - 总消费积分）
	const calculatedCurrentBalance = computed(() => {
	  return calculatedTotalEarned.value - calculatedTotalSpent.value;
	});



	// 计算总奖励积分
	const calculatedTotalBonus = computed(() => {
		return pointRecords.value
			.filter(record => record.type === 3 && (record.points || 0) > 0)
			.reduce((total, record) => total + (record.points || 0), 0);
	});

	// 计算总生成次数（消费记录数）
	const calculatedTotalGenerated = computed(() => {
		return pointRecords.value
			.filter(record => record.type === 2 && (record.points || 0) < 0)
			.length;
	});

	// 分页事件处理
	const handleSizeChange = (val) => {
		pageSize.value = val;
		currentPage.value = 1;
	};

	const handleCurrentChange = (val) => {
		currentPage.value = val;
	};

	// 获取头像URL
	const getAvatarUrl = (avatar) => {
		if (!avatar || avatar === '' || avatar === 'null' || avatar === 'undefined') {
			return '';
		}

		if (avatar.startsWith('http://') || avatar.startsWith('https://')) {
			return avatar;
		}

		const baseUrl = 'http://tool_back.connectsphere.top';
		return baseUrl + (avatar.startsWith('/') ? avatar : '/' + avatar);
	};

	// 处理图片加载错误
	const handleImageError = (event) => {
		event.target.src =
			'';
	};

	// 获取类型标签颜色
	const getTypeTag = (type) => {
		switch (type) {
			case 1:
				return 'success'; // 购买 - 绿色
			case 2:
				return 'danger'; // 消费 - 红色
			case 3:
				return 'warning'; // 活动赠送 - 橙色
			default:
				return 'info';
		}
	};

	// 获取类型文本
	const getTypeText = (type) => {
		switch (type) {
			case 1:
				return '购买';
			case 2:
				return '消费';
			case 3:
				return '活动赠送';
			default:
				return '其他';
		}
	};

	// 获取积分变动显示
	const getAmountDisplay = (row) => {
		// 使用正确的字段名 points
		const amount = row.points || 0;

		if (amount > 0) {
			return `+${amount}`;
		} else if (amount < 0) {
			return `${amount}`;
		} else {
			return '0';
		}
	};

	// 获取积分变动样式类
	const getAmountClass = (row) => {
		const amount = row.points || 0;
		return amount >= 0 ? 'positive' : 'negative';
	};

	// 格式化时间
	const formatDateTime = (dateTime) => {
		if (!dateTime) return '-';

		try {
			const date = new Date(dateTime);
			if (isNaN(date.getTime())) {
				const parsedDate = new Date(dateTime.replace(/-/g, '/'));
				if (!isNaN(parsedDate.getTime())) {
					return formatDate(parsedDate);
				}
				return dateTime;
			}
			return formatDate(date);
		} catch (e) {
			console.error('格式化时间出错:', e);
			return dateTime;
		}
	};

	const formatDate = (date) => {
		const year = date.getFullYear();
		const month = String(date.getMonth() + 1).padStart(2, '0');
		const day = String(date.getDate()).padStart(2, '0');
		const hours = String(date.getHours()).padStart(2, '0');
		const minutes = String(date.getMinutes()).padStart(2, '0');
		const seconds = String(date.getSeconds()).padStart(2, '0');

		return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
	};

	// 获取积分明细数据
	const fetchPointData = async () => {
		if (!props.openid) {
			ElMessage.error('缺少用户OpenID');
			return;
		}

		loading.value = true;

		try {
			console.log('正在获取积分明细，OpenID:', props.openid);

			// 首先尝试主要接口
			let response;
			try {
				response = await usersapi.getPointUsage(props.openid);
			} catch (primaryError) {
				console.log('主要接口失败，尝试备用接口:', primaryError);
				// 如果主要接口失败，尝试备用接口
				response = await usersapi.getPointUsageBackup(props.openid);
			}

			console.log('积分明细API响应:', response);

			if (response.data.code === 200) {
				const data = response.data.data;

				if (data) {
					// 根据API响应结构，数据在 data.data 中
					const actualData = data.data || data;

					console.log('原始API数据:', data);
					console.log('处理后的数据:', actualData);

					userInfo.value = {
						userId: actualData.userId || actualData.id,
						openid: actualData.openid,
						nickname: actualData.nickname,
						avatar: actualData.avatar,
						currentBalance: actualData.currentBalance || actualData.balance || 0,
						totalEarned: actualData.totalEarned || 0,
						totalSpent: actualData.totalSpent || 0,
						totalBonus: actualData.totalBonus || 0,
						totalGenerated: actualData.totalGenerated || 0
					};

					// 获取积分记录 - 尝试多种可能的字段名
					pointRecords.value = actualData.pointRecords ||
						actualData.records ||
						actualData.pointDetails ||
						actualData.details || [];

					console.log('积分明细数据:', userInfo.value);
					console.log('积分记录:', pointRecords.value);
					console.log('积分记录数量:', pointRecords.value.length);

					ElMessage.success('数据加载成功');
				} else {
					console.error('API返回的数据为空');
					ElMessage.error('API返回的数据为空');
				}
			} else {
				console.error('API返回错误:', response.data.msg);
				ElMessage.error(response.data.msg || '获取数据失败');
			}
		} catch (error) {
			console.error('获取积分明细失败:', error);
			console.error('错误详情:', error.response);

			// 更详细的错误信息
			if (error.response?.status === 404) {
				ElMessage.error('积分明细接口不存在，请检查后端是否实现了该接口');
			} else if (error.response?.status === 500) {
				ElMessage.error('服务器内部错误，请检查后端日志');
			} else {
				ElMessage.error('获取积分明细失败: ' + (error.response?.data?.message || error.message));
			}
		} finally {
			loading.value = false;
		}
	};



	// 刷新数据
	const refreshData = () => {
		fetchPointData();
	};

	// 组件挂载时获取数据
	onMounted(() => {
		fetchPointData();
	});
</script>

<style scoped>
	.point-detail-section {
		padding: 20px;
		display: flex;
		flex-direction: column;
		gap: 20px;
	}

	.user-info-card {
		border-radius: 12px;
		box-shadow: 0 4px 12px rgba(25, 118, 210, 0.1);
	}

	.user-info {
		display: flex;
		align-items: center;
		gap: 20px;
	}

	.avatar-container {
		flex-shrink: 0;
	}

	.user-avatar {
		width: 80px;
		height: 80px;
		border-radius: 50%;
		object-fit: cover;
		border: 3px solid #e3f2fd;
		box-shadow: 0 4px 12px rgba(25, 118, 210, 0.2);
		transition: all 0.3s ease;
	}

	.user-avatar:hover {
		transform: scale(1.05);
		box-shadow: 0 6px 16px rgba(25, 118, 210, 0.3);
	}

	.user-details {
		flex: 1;
	}

	.user-nickname {
		margin: 0 0 8px 0;
		font-size: 24px;
		font-weight: 600;
		color: #1976d2;
	}

	.user-id,
	.user-openid {
		margin: 4px 0;
		color: #666;
		font-size: 14px;
	}

	.balance-info {
		flex-shrink: 0;
	}

	.current-balance {
		text-align: center;
		padding: 20px;
		background: linear-gradient(135deg, #e3f2fd 0%, #bbdefb 100%);
		border-radius: 12px;
		box-shadow: 0 4px 12px rgba(25, 118, 210, 0.2);
	}

	.balance-label {
		display: block;
		font-size: 14px;
		color: #1976d2;
		margin-bottom: 8px;
	}

	.balance-value {
		display: block;
		font-size: 32px;
		font-weight: bold;
		color: #1565c0;
	}

	.stats-card {
		border-radius: 12px;
		box-shadow: 0 4px 12px rgba(25, 118, 210, 0.1);
	}

	.stats-grid {
		display: grid;
		grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
		gap: 20px;
	}

	.stat-item {
		text-align: center;
		padding: 20px;
		background: #f8f9fa;
		border-radius: 8px;
		border: 1px solid #e3f2fd;
		transition: all 0.3s ease;
	}

	.stat-item:hover {
		background: #e3f2fd;
		transform: translateY(-2px);
		box-shadow: 0 4px 12px rgba(25, 118, 210, 0.2);
	}

	.stat-value {
		font-size: 28px;
		font-weight: bold;
		color: #1976d2;
		margin-bottom: 8px;
	}

	.stat-label {
		font-size: 14px;
		color: #666;
	}

	.records-card {
		border-radius: 12px;
		box-shadow: 0 4px 12px rgba(25, 118, 210, 0.1);
	}

	.card-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.table-container {
		margin-bottom: 20px;
	}

	.positive {
		color: #4caf50;
		font-weight: bold;
	}

	.negative {
		color: #f44336;
		font-weight: bold;
	}

	.pagination-container {
		display: flex;
		justify-content: center;
		align-items: center;
		padding: 20px 0;
		background: #fff;
		border-radius: 8px;
		margin-top: 16px;
		box-shadow: 0 2px 8px rgba(25, 118, 210, 0.1);
	}

	/* 响应式设计 */
	@media (max-width: 768px) {
		.user-info {
			flex-direction: column;
			text-align: center;
		}

		.stats-grid {
			grid-template-columns: repeat(2, 1fr);
		}

		.balance-value {
			font-size: 24px;
		}

		.stat-value {
			font-size: 20px;
		}
	}

	.empty-state {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 60px 20px;
		color: #909399;
	}

	.empty-state p {
		margin-top: 16px;
		font-size: 16px;
	}
</style>